import os
import time
import utime
import network
from machine import Pin
from machine import ADC
p_motor = Pin(16, Pin.OUT)    # create output pin on GPIO0
p_led = Pin(2, Pin.OUT)    # create output pin on GPIO0
plant_adc = ADC(0)            # create ADC object on ADC pin
def  test(x):
	Rf1 = 330
	Rf2 = 150
	print(3.3*(Rf2/(Rf1+Rf2)))
	Rb=(Rf2*x)/(Rf2+x)
	out = Rb*(3.3 / (Rf1+Rb))
	print("x=",out)
def  plant_get_Soil_humidity():
	adc_v = plant_adc.read()              # read value, 0-1024
	print(utime.time(),":soil humidity=", adc_v)
	return  adc_v
def  motor_ctrl(param):
	if param == 1:
		print("start motor")
		p_motor.on()  # set pin to "on" (high) level
		time.sleep(2)
		p_motor.off()
	else:
		print("stop motor")
		p_motor.off()
humidity_count = 0
humidity_avg = 0
def  humidity_poll():
	global humidity_count
	global humidity_avg
	humidity_count +=1
	if humidity_count >= 3:
		humidity_avg=humidity_avg/3
		print('humidity_avg=',humidity_avg)
		if humidity_avg > 600:
			motor_ctrl(1)
		else:
			motor_ctrl(0)
			# time.sleep(1)
		humidity_count = 0
		humidity_avg = 0
	humidity_avg = humidity_avg +  plant_get_Soil_humidity()
	

def  show_live_led():
	if p_led.value():
		p_led.off()
		# motor_ctrl(0)
	else:
		p_led.on()
		# motor_ctrl(1)
	# print("led=",p_led.value())
def  main_poll():
	motor_ctrl(0)
	while 1:
		humidity_poll()
		show_live_led()
		time.sleep(1)
def config_ap_init():
	ap = network.WLAN(network.AP_IF)
	ap.config(essid='micropytho_bcg', password='bcg12345')
	ap.active(True)
#Automatic watering system ，自动浇花
if __name__ == '__main__':
	# config_ap_init()
	main_poll()

